from django.db import models
from django.contrib.auth import get_user_model
import secrets

User = get_user_model()

class Project(models.Model):
    STATUS_CHOICES = [
        ('active', '运行中'),
        ('inactive', '已停止'),
        ('maintenance', '维护中'),
    ]
    
    name = models.CharField(max_length=100, verbose_name='项目名称')
    description = models.TextField(blank=True, verbose_name='项目描述')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='active', verbose_name='状态')
    api_key = models.CharField(max_length=128, unique=True, verbose_name='API密钥')  # 改为128
    owner = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='所有者')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '项目'
        verbose_name_plural = '项目'
        ordering = ['-created_at']
    
    def save(self, *args, **kwargs):
        if not self.api_key:
            self.api_key = f"lwh_{secrets.token_hex(32)}"
        super().save(*args, **kwargs)
    
    def regenerate_api_key(self):
        """重新生成API密钥"""
        self.api_key = f"lwh_{secrets.token_hex(32)}"
        self.save()
        return self.api_key
    
    def __str__(self):
        return self.name